import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;


public class CodeDescriptionPair {

	
	public final static String TABLE_TYPE = "assetTypes";
	public final static String TABLE_MINTENANCE = "maintenanceSchedules";
	public final static String TABLE_FINANCIAL = "financialValues";
	public final static String TABLE_CONFIDENTIALITY = "confidentialityValues";
	public final static String TABLE_INTEGRITY = "integrityValues";
	public final static String TABLE_AVAILABILITY = "availabilityValues";
	public final static String TABLE_CLASSIFICATION = "assetClassifications";
	
	public static ArrayList<CodeDescriptionPair> getCodeDescriptionPairsFor(String tableName)
	{
		ArrayList<CodeDescriptionPair> codeDescriptionPairs = new ArrayList<CodeDescriptionPair>();
		
		String query = "SELECT * FROM "+tableName+";";
		Connection con = DBConnector.getConnection();
		
		ResultSet rs = DBConnector.executeQuery(con, query);
			
		try {
			while(rs.next())
				codeDescriptionPairs.add(new CodeDescriptionPair(rs.getString("code"), rs.getString("description"), tableName));
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		
		try {
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return codeDescriptionPairs;
	}	
	
	private String code;
	private String description;
	private String sourceTableName;
	
	public CodeDescriptionPair(String code, String description, String sourceTableName)
	{
		this.code = code;
		this.description = description;
		this.sourceTableName = sourceTableName;
	}
	
	public String getCode()
	{
		return code;
	}
	
	public void setCode(String code)
	{		
		//Check if code is valid
		String query = "SELECT count(*) FROM "+sourceTableName+" WHERE code = \""+code+"\";";
		Connection con = DBConnector.getConnection();
		int count;
		try {
			count = Integer.parseInt(DBConnector.executeQueryWithSingleValue(con, query));
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			count = 1; //make the code invalid if there was an exception by setting count to 1
		}
		
		if(count == 0)
			this.code = code;	
	}
	
	public String getDescription()
	{
		return description;
	}
	
}
